package com.yhq.basic.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Set;

/**
 * @author hqyin
 * @date 2025/6/5 9:35 AM
 */
public class NIOServer {
    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();

        ServerSocketChannel channel = ServerSocketChannel.open();
        channel.configureBlocking(false);
        channel.register(selector, SelectionKey.OP_ACCEPT);

        ServerSocket serverSocket = channel.socket();
        InetSocketAddress address = new InetSocketAddress("127.0.0.1",8888);
        serverSocket.bind(address);

        while (true) {
            selector.select();
            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> keyIterator = keys.iterator();
            while (keyIterator.hasNext()) {
                SelectionKey key = keyIterator.next();
                if(key.isAcceptable()) {
                    ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();

                    SocketChannel client = serverSocketChannel.accept();
                    client.configureBlocking(false);
                    client.register(selector,SelectionKey.OP_READ);
                    System.out.println("client:已连接：port:"+client.socket().getPort());
                } else if(key.isReadable()) {
                    SocketChannel sChannel = (SocketChannel) key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    sChannel.read(buffer);
                    buffer.flip();
                    CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
                    String msg = decoder.decode(buffer).toString();
                    System.out.println(msg);
                    sChannel.register(selector,SelectionKey.OP_WRITE);
               } else if(key.isWritable()) {
                    SocketChannel sChannel = (SocketChannel) key.channel();
                    String msg = "server:recieved msg";
                    CharsetEncoder encoder = StandardCharsets.UTF_8.newEncoder();
                    sChannel.write(encoder.encode(CharBuffer.wrap(msg)));
                    sChannel.register(selector,SelectionKey.OP_READ);
                }

                keyIterator.remove();
            }
        }


    }



}
